﻿
using System;
using System.Collections.Generic;
using System.Text;

using YouHP.Utility;
using YouHP.BLL;
using YouHP.Model;

namespace YouHP.Pages.WeightHistory
{
    public class WeightAjax : YouHP.Pages.BasePage
    {

        protected override void ShowPage()
        {
            base.ShowPage();
            if (ErrorCount > 0) return;

            if (IsPost == false) HandleGet();
        }

        protected void HandleGet()
        {
            if (UserData.Id <= 0) 
                return;

            PatientRecordInfo prData = PatientBLL.Instance.GetPatientRecordInfo(UserData.Id);
            if (prData.Id <= 0) 
                return;

            List<WeightHistoryInfo> lst = null;
            double height = PatientBLL.Instance.GetPatientHeight(UserData.Id);
            if (height >= 0)
            {
                lst = PatientBLL.Instance.GetWeightHistoryList(prData.Id, Constants.ALLMODE);
            }

            MakeWeightGraphData(prData, lst, height);
        }

        private void MakeWeightGraphData(PatientRecordInfo prData, List<WeightHistoryInfo> lst,double height)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("&SingleWeight=1&\r\n");
            sb.AppendFormat("&StartDate={0:yyyy-MM-dd}&\r\n", prData.StartDate);
            sb.AppendFormat("&DosageDate={0:yyyy-MM-dd}&\r\n", prData.ConfirmDate);
            sb.AppendFormat("&UpdateDate={0:yyyy-MM-dd}&\r\n", prData.UpdateDate);

            if (height > 0)
            {
                sb.AppendFormat("&Var=体重;{0}&\r\n", lst.Count);
                for(int i=0; i<lst.Count; i++)
                {
                    WeightHistoryInfo info = lst[i];
                    sb.AppendFormat("&Data_{0}={1:yyyy-MM-dd};{2}&\r\n",
                        i,
                        info.RecordDate,
                        info.DataValue
                        );
                }
            }
            else
            {
                sb.AppendFormat("&Var=体重;0&\r\n");  //无效的体重信息，因为没有身高
            }

            ResponseXML(sb);
        }

        private void ResponseXML(StringBuilder sb)
        {
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = "Text/html";
            System.Web.HttpContext.Current.Response.Expires = 0;

            System.Web.HttpContext.Current.Response.Write(sb.ToString());
            System.Web.HttpContext.Current.Response.End();
        }
    }
}